package com.ebraga.trackerclub.android.view.service;

import java.util.Calendar;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.IBinder;
import android.util.Log;

import com.ebraga.trackerclub.android.R;
import com.ebraga.trackerclub.android.exception.handler.BackofficeHandlerException;
import com.ebraga.trackerclub.android.handler.service.LoginServiceHandler;
import com.ebraga.trackerclub.android.handler.service.PositionServiceHandler;
import com.ebraga.trackerclub.android.util.ISmartServiceConstants;
import com.ebraga.trackerclub.android.util.SynchManager;
import com.ebraga.trackerclub.android.util.UtilView;
import com.ebraga.trackerclub.android.util.api.AndroidContext;
import com.ebraga.trackerclub.android.util.core.AndroidContextImpl;
import com.ebraga.trackerclub.android.view.MyLocationListener;
import com.ebraga.trackerclub.android.vo.PositionVO;
import com.ebraga.trackerclub.android.vo.UserVO;

public class PositionService extends IntentService {

	int mStartMode;       // indicates how to behave if the service is killed
	IBinder mBinder;      // interface for clients that bind
	boolean mAllowRebind; // indicates whether onRebind should be used

	private LocationListener locationListener;
	private LocationManager lm;
	private long TIME_TO_TRY_GET_POSITION_WAIT = 1000L * 10;
	private int TIMES_TO_TRY_GET_POSITION = 2;

	public PositionService() {
		super(PositionService.class.getName());

	}	
	
	@Override
	public void onHandleIntent(Intent intent) {
		
		locationListener = new MyLocationListener(getApplicationContext());
		
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MILLISECOND, (int) SynchManager.INTERVAL_GPS);
		SynchManager.setRepeatingAlarmForPosition(this, cal.getTimeInMillis());
		
		sendPositionData();
		

	}
	

	private void startLocationListener() {

		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

			lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
					locationListener);

		}

		if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
					locationListener);

		}		

	}
	
	private void stopLocationListener() {
		 lm.removeUpdates(locationListener);
	}

	private void sendPositionData() {
		try {
			
			validate();			
			
			//Inicia o serviço para recuperar a posição GPS
			startLocationListener();
			
			//Aguarda tempo para tentar recuperar a posição de GPS
			int count = 1;
			synchronized (this) {
				
				while (retrivePositionContext() == null && count < TIMES_TO_TRY_GET_POSITION) {
					wait(TIME_TO_TRY_GET_POSITION_WAIT);
					count++;
				}
				
			}
			
			PositionVO positionVO = retrievePosition();
			
			//Finaliza o serviço
			stopLocationListener();			

			if (positionVO != null) {
				
				PositionServiceHandler positionServiceHandler = new PositionServiceHandler(getAndroidContext());

				positionServiceHandler.sendPositionData(positionVO);
				
			}

		} catch (BackofficeHandlerException e) {
			Log.d(getPackageName(), e.getMessage());
		} catch (Exception e) {
			Log.d(getPackageName(), e.getMessage());
		}

	}


    private boolean validate() {
    	
        boolean isValid = true;
        try {
	        LoginServiceHandler loginServiceHandler = new LoginServiceHandler(getAndroidContext());
	        UserVO userVO = loginServiceHandler.lastLogin();
	        
			if (!UtilView.gpsActived(getBaseContext())) {
				UtilView.sendNotification(getBaseContext(), getString(R.string.warn_gps_off), ISmartServiceConstants.NOTIFICATION_ID.GPS_DISABLED);
				isValid = false;
			}	        
        } catch (BackofficeHandlerException e) {
        	Log.d(getPackageName(), e.getMessage());
        }
		
		return isValid;
        
    }	

	//Recupera dados do ultimo usuário logado
	private UserVO retrieveLastUserLogged() throws BackofficeHandlerException {

		LoginServiceHandler loginServiceHandler = new LoginServiceHandler(getAndroidContext());
		UserVO userVO = loginServiceHandler.lastLogin();

		return userVO;

	}


	//Recupera posição GPS
	private PositionVO retrievePosition() throws BackofficeHandlerException {
		
		UserVO userVO = retrieveLastUserLogged();

		if (userVO == null) {
			return null;
		}
		
		PositionVO positionVO = retrivePositionContext();
		
		if (positionVO != null) {
			positionVO.setImei(userVO.getImei());
		} 
		
		return positionVO;

	}

	private PositionVO retrivePositionContext() {
		PositionVO positionVO = ((MyLocationListener) locationListener).acceptablePosition();
		return positionVO;
	}



	private AndroidContext getAndroidContext() {
		AndroidContext context = new AndroidContextImpl();

		context.setContext(getApplicationContext());
		return context;
	}		


}